<template>
    <div class="register-or-login-container">

        <div class="register-or-login-nav">

            <n-menu v-model:value="selectKey" :options="menuOptions" :on-update:value="updateSelectKey" />

        </div>

        <!-- 登录内容 -->
        <div class="login-content" v-show="selectKey == 'login'">

            <n-form ref="loginFormRef" :label-width="80" :model="loginFrom" :rules="loginRules">

                <n-form-item label="用户名：" path="username">
                    <n-input class="inputStyle" v-model:value="loginFrom.username" placeholder="输入用户名" />
                </n-form-item>

                <n-form-item label="密码：" path="password">
                    <n-input class="inputStyle" type="password" v-model:value="loginFrom.password" show-password-on="mousedown" @keydown.enter="loginUserBtn" placeholder="输入密码" />
                </n-form-item>

                <n-form-item>
                    <div style="display: flex;justify-content: space-between;width: 600px;align-items: center;">
                        <n-button quaternary type="tertiary" @click="router.push({ name: `${usePlayConfig.playListMode}` })">
                            返回
                        </n-button>
                        <n-button quaternary type="info" @click="loginUserBtn">
                            登录
                        </n-button>
                    </div>
                </n-form-item>

            </n-form>

        </div>

        <!-- 注册内容 -->
        <div class="register-content" v-show="selectKey == 'register'">

            <n-form ref="registerFormRef" :label-width="80" :model="registerFrom" :rules="registerRules">

                <n-form-item label="用户名：" path="username">
                    <n-input class="inputStyle" v-model:value="registerFrom.username" placeholder="输入用户名" />
                </n-form-item>

                <n-form-item label="密码：" path="password">
                    <n-input class="inputStyle" type="password" v-model:value="registerFrom.password" show-password-on="mousedown" @input="handlePasswordInput" @keydown.enter.prevent placeholder="输入密码" />
                </n-form-item>

                <n-form-item ref="rPasswordFormItemRef" label="再次确认：" path="reenteredPassword">
                    <n-input class="inputStyle" type="password" v-model:value="registerFrom.reenteredPassword" show-password-on="mousedown" placeholder="再次输入密码" />
                </n-form-item>

                <n-form-item>
                    <div style="display: flex;justify-content: space-between;width: 600px;align-items: center;">
                        <n-button quaternary type="tertiary" @click="router.push({ name: `${usePlayConfig.playListMode}` })">
                            返回
                        </n-button>
                        <n-button quaternary type="info" @click="registerUserBtn">
                            注册
                        </n-button>
                    </div>
                </n-form-item>

            </n-form>

        </div>

    </div>
</template>
    
<script setup lang='ts'>
import { FormInst, FormItemInst, FormItemRule, FormRules, MenuOption, useMessage } from 'naive-ui';
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { usePlayConfigStore, userInfoStore, useSystemConfigStore } from '../../store';
import { checkUserName, registerUser, loginUser } from '../../ajax'
import { refreshUserIpInfo, refreshUserClientInfo, importPlayListMode } from '../../util/calculate'

const router = useRouter()
const usePlayConfig = usePlayConfigStore()
const useSystemConfig = useSystemConfigStore()
const userInfo = userInfoStore()
const message = useMessage()
const registerFormRef = ref<FormInst | null>(null)
const loginFormRef = ref<FormInst | null>(null)
const rPasswordFormItemRef = ref<FormItemInst | null>(null)

// 菜单
const selectKey = ref('login')
const menuOptions: MenuOption[] = [
    {
        label: '登录',
        key: 'login',
    },
    {
        key: 'divider-1',
        type: 'divider',
        props: {

        }
    },
    {
        label: '注册',
        key: 'register',
    }
]
const updateSelectKey = (key: 'register' | 'login') => { // 切换菜单
    selectKey.value = key
}

/* ***********************************注册*********************************** */
// 用户注册表单信息
interface RegisterForm {
    username: string
    password: string
    reenteredPassword: string
}
const registerFrom = ref<RegisterForm>({
    username: '',
    password: '',
    reenteredPassword: '',
})
// 注册验证规则
const registerRules: FormRules = {
    username: [
        {
            required: true,
            message: '用户名不能空',
            validator: (_rule: FormItemRule, value: string) => {
                registerFrom.value.username = value.trim()
                if (value.trim() == '') {
                    return false
                } else {
                    return true
                }
            },
            trigger: ['input']
        },
        {
            trigger: 'blur',
            validator: (_rule: FormItemRule, value: string) => {
                return new Promise<void>(async (resolve, reject) => {
                    const { data } = await checkUserName(value)
                    if (data.code == 1) {
                        reject(Error(data.message))
                    } else {
                        resolve()
                    }
                })
            }
        }
    ],
    password: [
        {
            required: true,
            validator: (_rule: FormItemRule, value: string) => {
                if (value.length < 8 || value.length > 10) {
                    return new Error('密码长度应该为8-10位')
                } else {
                    const reg = new RegExp('^(?=.*\\d)(?=.*[A-Z])(?=.*[a-z])[a-zA-Z0-9]{6,10}$', 'g')
                    if (!reg.test(value)) {
                        return new Error('必须包含大小写字母和数字的组合，不能使用特殊字符，长度在 8-10 之间')
                    }
                    return true
                }
            },
            trigger: ['input', 'blur']
        }
    ],
    reenteredPassword: [{
        required: true,
        validator: (_rule: FormItemRule, value: string) => {
            if (value.length < 8 || value.length > 10) {
                return new Error('密码长度应该为8-10位')
            } else if (value.length !== registerFrom.value.password?.length) {
                return new Error('两次密码长度不相同')
            } else {
                if (value !== registerFrom.value.password) {
                    return new Error('两次密码必须相同')
                }
                return true
            }
        },
        trigger: ['input', 'blur', 'password-input']
    }]
}
// 输入密码时会影响验证再次输入密码框
const handlePasswordInput = () => {
    if (registerFrom.value.reenteredPassword) {
        rPasswordFormItemRef.value?.validate({ trigger: 'password-input' })
    }
}
// 注册
const registerUserBtn = () => {
    registerFormRef.value?.validate(async (errors) => { // 验证全部输入框
        if (!errors) { // 全部输入框没有错误
            // 开启全屏加载
            useSystemConfig.changeLoading(true, '注册中')
            // 请求注册
            const { data } = await registerUser(registerFrom.value.username, registerFrom.value.password)
            if (data.code == 0) { // 注册成功
                // 提示注册成功
                message.info(`${data.message}`)
                useSystemConfig.changeLoading(false, '加载中')
                // 用户信息本地存储
                userInfo.changeUserInfo(data.userInfo._id, data.userInfo.username, data.userInfo.roles, data.userInfo.joinDate, data.userInfo.level, data.userInfo.cloundSize, data.userInfo.useCloundSize, data.userInfo.cloundAuth)
                userInfo.changeUserToken(data.userInfo.token, true)
                // 上传用户客户端IP和地址
                const ipResult = await refreshUserIpInfo()
                if (ipResult.status) { //上传用户客户端信息成功
                    const addressResult = await refreshUserClientInfo(ipResult._ip)
                    if (addressResult.status) {
                        userInfo.changeUserClientAndIp(ipResult._ip, ipResult.loginDate, addressResult._client)
                    }
                    router.replace({ name: `${usePlayConfig.playListMode}` })
                }
            } else { // 注册失败
                useSystemConfig.changeLoading(false, '加载中')
                message.warning(data.message)
            }
        } else { // 部分输入框有错误
            message.error('注册信息验证失败')
        }
    })
}

/* ***********************************登录*********************************** */
// 用户登录表单信息
interface LoginForm {
    username: string,
    password: string
}
const loginFrom = ref<LoginForm>({
    username: '',
    password: ''
})
// 登录规则
const loginRules: FormRules = {
    username: [
        {
            required: true,
            message: '用户名不能空',
            validator: (_rule: FormItemRule, value: string) => {
                loginFrom.value.username = value.trim()
                if (value.trim() == '') {
                    return false
                } else {
                    return true
                }
            },
            trigger: ['input']
        }
    ],
    password: [
        {
            required: true,
            validator: (_rule: FormItemRule, value: string) => {
                if (value.length < 8 || value.length > 10) {
                    return new Error('密码长度应该为8-10位')
                } else {
                    const reg = new RegExp('^(?=.*\\d)(?=.*[A-Z])(?=.*[a-z])[a-zA-Z0-9]{6,10}$', 'g')
                    if (!reg.test(value)) {
                        return new Error('必须包含大小写字母和数字的组合，不能使用特殊字符，长度在 8-10 之间')
                    }
                    return true
                }
            },
            trigger: ['input', 'blur']
        }
    ]
}
// 登录
const loginUserBtn = () => {
    loginFormRef.value?.validate(async (errors) => { // 验证全部输入框
        if (!errors) { // 全部输入框没有错误
            // 开启全屏加载
            useSystemConfig.changeLoading(true, '登录中')
            // 请求登录
            const { data } = await loginUser(loginFrom.value.username, loginFrom.value.password)
            if (data.code == 0) { // 登录成功
                // 提示登录成功
                message.info(`${data.message}`)
                // 关闭加载框
                useSystemConfig.changeLoading(false, '加载中')
                // 用户信息本地存储
                userInfo.changeUserInfo(data.userInfo._id, data.userInfo.username, data.userInfo.roles, data.userInfo.joinDate, data.userInfo.level, data.userInfo.cloundSize, data.userInfo.useCloundSize, data.userInfo.cloundAuth)
                userInfo.changeUserToken(data.userInfo.token, true)
                await importPlayListMode('likePlayList', data.userInfo.likePlayList)
                // 上传用户客户端IP和地址
                const ipResult = await refreshUserIpInfo()
                if (ipResult.status) { //上传用户客户端信息成功
                    const addressResult = await refreshUserClientInfo(ipResult._ip)
                    if (addressResult.status) {
                        userInfo.changeUserClientAndIp(ipResult._ip, ipResult.loginDate, addressResult._client)
                    }
                    router.replace({ name: `${usePlayConfig.playListMode}` })
                }
            } else { // 登录失败
                // 关闭全屏加载
                useSystemConfig.changeLoading(false, '加载中')
            }
        } else { // 部分输入框有错误
            message.error('登录信息验证失败')
        }
    })
}

</script>
    
<style scoped lang="less">
.register-or-login-container {
    display: flex;
    justify-content: center;

    .register-or-login-nav {
        margin-right: 20px;
    }


}

.inputStyle {
    width: 600px;
}
</style>